package com.cccyy.thread;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.util.concurrent.*;

public class ThreadSample {
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                .setNameFormat("activity-thread-%d").build();
        // 线程池
        ExecutorService pool = new ThreadPoolExecutor(5, 5, 5, TimeUnit.MILLISECONDS,
                new ArrayBlockingQueue<>(500), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
        CompletableFuture<String> query1 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "query1";
        }, pool);
        CompletableFuture<String> query2 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "query2";
        }, pool);
        CompletableFuture<String> query3 = CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(550);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "query3";
        }, pool);
        try {
            // 资源获取完成，走后续主逻辑 executeNext(query1.get(),query2.get(),query3.get(2,TimeUnit.SECONDS));
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("耗时:" + (System.currentTimeMillis() - start));
        pool.shutdown();
    }

    private static void executeNext(String a1, String a2, String a3) {
        System.out.println(a1);
        System.out.println(a2);
        System.out.println(a3);
    }

}
